package com.qilu.pe.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatEditText;

import com.alipay.sdk.app.PayTask;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.qilu.pe.R;
import com.qilu.pe.base.Base2Activity;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.base.PayResult;
import com.qilu.pe.dao.bean.ExpertUser;
import com.qilu.pe.dao.bean.OrderResult;
import com.qilu.pe.dao.bean.UPayInfo;
import com.qilu.pe.dao.bean.WxPayInfo;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.AlertUtil;
import com.qilu.pe.support.util.Logg;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.ToastUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 申请专家解读
public class ConfirmExpertExplainActivity extends Base2Activity {
    private AppCompatEditText et_height, et_weight, et_heart, et_temp, et_shrink;
    private AppCompatEditText et_relax, et_family, et_treat, et_pill, et_allergy;
    private AppCompatEditText et_content;// 不适及临床表现
    private TextView tv_name, tv_ok;

    private String expert, orderId, sid;
    private String height, weight, heart, temp, shrink, relax, family, treat, pill, allergy;
    private String content, imgs;// 不适及临床表现 上传的图片

    private ExpertUser currExpert;// 记录当前选择的专家

    IWXAPI msgApi;
    private String order_num;// 创建专家解读的订单号

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_confirm_expert_explain;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        et_height = findViewById(R.id.et_height);
        et_weight = findViewById(R.id.et_weight);
        et_heart = findViewById(R.id.et_heart);
        et_temp = findViewById(R.id.et_temp);
        et_shrink = findViewById(R.id.et_shrink);
        et_relax = findViewById(R.id.et_relax);
        et_family = findViewById(R.id.et_family);
        et_treat = findViewById(R.id.et_treat);
        et_pill = findViewById(R.id.et_pill);
        et_allergy = findViewById(R.id.et_allergy);
        et_content = findViewById(R.id.et_content);
        tv_name = findViewById(R.id.tv_name);
        tv_ok = findViewById(R.id.tv_ok);

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            orderId = bundle.getString("orderId");
            sid = bundle.getString("sid");
        }

        setHeadTitle("申请专家解读");

        setListeners();

        alert = new AlertDialog.Builder(this, R.style.Dialog_FS).create();

        msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(Config.WX_APP_ID);
    }

    private void setListeners() {
        setOnClickListener(tv_name, tv_ok);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_name) {// 点击先请求专家列表,再弹出专家选择器
            hideProgress();
            reqExpertList();
            showProgress();
        }
        if (v == tv_ok) {// 去支付
            height = et_height.getText().toString().trim();
            weight = et_weight.getText().toString().trim();
            heart = et_heart.getText().toString().trim();
            temp = et_temp.getText().toString().trim();
            shrink = et_shrink.getText().toString().trim();
            relax = et_relax.getText().toString().trim();
            family = et_family.getText().toString().trim();
            treat = et_treat.getText().toString().trim();
            pill = et_pill.getText().toString().trim();
            allergy = et_allergy.getText().toString().trim();
            content = et_content.getText().toString().trim();

            if (TextUtils.isEmpty(height)) {
                ToastUtils.showShort("请输入您的身高");
                return;
            }
            if (TextUtils.isEmpty(weight)) {
                ToastUtils.showShort("请输入您的体重");
                return;
            }
            if (TextUtils.isEmpty(heart)) {
                ToastUtils.showShort("请输入您的心率");
                return;
            }
            if (TextUtils.isEmpty(temp)) {
                ToastUtils.showShort("请输入您的体温");
                return;
            }
            if (TextUtils.isEmpty(shrink)) {
                ToastUtils.showShort("请输入您的收缩压");
                return;
            }
            if (TextUtils.isEmpty(relax)) {
                ToastUtils.showShort("请输入您的舒张压");
                return;
            }
//            if (TextUtils.isEmpty(family)) {
//                ToastUtils.showShort("请输入家族史");
//                return;
//            }
//            if (TextUtils.isEmpty(treat)) {
//                ToastUtils.showShort("请输入治疗史");
//                return;
//            }
//            if (TextUtils.isEmpty(pill)) {
//                ToastUtils.showShort("请输入用药史");
//                return;
//            }
//            if (TextUtils.isEmpty(allergy)) {
//                ToastUtils.showShort("请输入过敏史");
//                return;
//            }
//            if (TextUtils.isEmpty(content)) {
//                ToastUtils.showShort("请填写不适及临床表现");
//                return;
//            }

            imgs = "{}";
            family = "{" + family + "}";
            treat = "{" + treat + "}";
            pill = "{" + pill + "}";
            allergy = "{" + allergy + "}";

            hideProgress();
            reqCreateExpertOrder();
            showProgress();
        }
    }

    private Disposable reqCreateExpertOrder() {
        String blood = "{" + shrink + "," + relax + "}";
        return APIRetrofit.getDefault().reqCreateExpertOrder(Global.HEADER, expert, height, weight
                , heart, temp, blood, family, treat, pill, allergy, content, orderId, sid, imgs)
                .compose(RxUtil.<BaseResult2<OrderResult>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<OrderResult>>() {
                    @Override
                    public void accept(BaseResult2<OrderResult> result2) throws Exception {
                        hideProgress();
                        ToastUtils.showShort(result2.getMsg());
                        if (result2.isSuccess()) {
                            order_num = result2.getData().getOrder_num();
                            showDialog();
                        } else {

                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqExpertList() {
        return APIRetrofit.getLs().reqExpertList(Global.HEADER, 1, 999999)
                .compose(RxUtil.<BaseResult2<List<ExpertUser>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<ExpertUser>>>() {
                    @Override
                    public void accept(BaseResult2<List<ExpertUser>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            typeList = (ArrayList<ExpertUser>) listBaseResult2.getData();
                            initCustomOptionPicker();
                            pvCustomOptions.show();
                        } else {

                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private ArrayList<ExpertUser> typeList = new ArrayList<>();

    private OptionsPickerView pvCustomOptions;// 条件选择器

    /**
     * @description 注意事项：自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针。
     * 具体可参考demo 里面的两个自定义layout布局。
     */
    private void initCustomOptionPicker() {//条件选择器初始化，自定义布局
        pvCustomOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = typeList.get(options1).getPickerViewText();
                tv_name.setText(tx);
                currExpert = typeList.get(options1);
                expert = currExpert.getId();
            }
        }).setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = v.findViewById(R.id.tv_finish);
                ImageView ivCancel = v.findViewById(R.id.iv_cancel);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions.returnData();
                        pvCustomOptions.dismiss();
                    }
                });

                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions.dismiss();
                    }
                });
            }
        })
                .isDialog(true)
                .setOutSideCancelable(false)
                .build();

        pvCustomOptions.setPicker(typeList);//添加数据
    }

    private AlertDialog alert;// 弹窗
    private View alert_view;
    String payType = "2";// 支付方式 1 微信,2 支付宝,3 银联支付,4 余额支付

    public void showDialog() {// 弹窗界面
        alert.show();
        alert_view = View.inflate(this, R.layout.layout_alert_choose_pay_type, null);

        final RadioButton cb_ali = alert_view.findViewById(R.id.cb_ali);
        final RadioButton cb_wx = alert_view.findViewById(R.id.cb_wx);
        final RadioButton cb_union = alert_view.findViewById(R.id.cb_union);
        final RadioButton cb_balance = alert_view.findViewById(R.id.cb_balance);
        final TextView tv_balance0 = alert_view.findViewById(R.id.tv_balance0);// 显示余额数量

        RelativeLayout rl_ali = alert_view.findViewById(R.id.rl_ali);
        RelativeLayout rl_wechat = alert_view.findViewById(R.id.rl_wechat);
        RelativeLayout rl_union_pay = alert_view.findViewById(R.id.rl_union_pay);
        RelativeLayout rl_balance = alert_view.findViewById(R.id.rl_balance);

        tv_balance0.setText("余额支付 (¥" + Global.ORG_BALANCE + ")");

        rl_ali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(true);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        cb_ali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(true);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        rl_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(true);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        cb_wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(true);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        rl_union_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(true);
                cb_balance.setChecked(false);
            }
        });
        cb_union.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(true);
                cb_balance.setChecked(false);
            }
        });
        rl_balance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(true);
            }
        });
        cb_balance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(true);
            }
        });

        alert_view.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cb_ali.isChecked()) {
                    payType = "2";
                } else if (cb_wx.isChecked()) {
                    payType = "1";
                } else if (cb_union.isChecked()) {
                    payType = "3";
                } else if (cb_balance.isChecked()) {
                    payType = "4";
                }
                if (cb_ali.isChecked()) {// 支付宝
                    hideProgress();
                    reqAliPayInfo();
                    showProgress();
                } else if (cb_wx.isChecked()) {// 微信
                    hideProgress();
                    reqWxPayInfo();
                    showProgress();
                } else if (cb_union.isChecked()) {// 银联
                    hideProgress();
                    reqUPayPayInfo();
                    showProgress();
                } else if (cb_balance.isChecked()) {
                    hideProgress();
                    reqBalancePayInfo();
                    showProgress();
                }
                alert.dismiss();
            }
        });

        AlertUtil.setAlertBottomInStyle(alert.getWindow(), alert_view, this);
    }

    private Disposable reqBalancePayInfo() {
        if (TextUtils.isEmpty(order_num)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqExpertOrderPayBalance(Global.HEADER, order_num, payType)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            startActivity(PaySuccessActivity.class);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_balance = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqUPayPayInfo() {
        if (TextUtils.isEmpty(order_num)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqExpertOrderPayUpay(Global.HEADER, order_num, payType)
                .compose(RxUtil.<BaseResult2<UPayInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<UPayInfo>>() {
                    @Override
                    public void accept(BaseResult2<UPayInfo> baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            uPay(baseResult2.getData().getTn());
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_upay = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqWxPayInfo() {
        if (TextUtils.isEmpty(order_num)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqExpertOrderPayWx(Global.HEADER, order_num, payType)
                .compose(RxUtil.<BaseResult2<WxPayInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<WxPayInfo>>() {
                    @Override
                    public void accept(BaseResult2<WxPayInfo> baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            wxPay(baseResult2);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_wx = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取微信支付信息错误");
                    }
                });
    }

    private Disposable reqAliPayInfo() {
        if (TextUtils.isEmpty(order_num)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqExpertOrderPayAli(Global.HEADER, order_num, payType)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            String orderInfo = (String) baseResult2.getData();
                            aliPay(orderInfo);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_ali = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 调起银联支付
    private void uPay(String tn) {
        // “00” – 银联正式环境
        // “01” – 银联测试环境，该环境中不发生真实交易
        String serverMode = "01";
        UPPayAssistEx.startPay(Arad.app, null, null, tn, serverMode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        String str = data.getExtras().getString("pay_result");
        if (str.equalsIgnoreCase("success")) {
            //显示支付结果
            ToastUtils.showShort("银联支付成功");
            // 结果为成功时，建议去商户后台查询一下再展示成功
        } else if (str.equalsIgnoreCase("fail")) {
            ToastUtils.showShort("银联支付失败");
        } else if (str.equalsIgnoreCase("cancel")) {
            ToastUtils.showShort("您取消了银联支付");
        }
    }

    // 调起微信支付
    private void wxPay(BaseResult2<WxPayInfo> baseResult2) {
        WxPayInfo wxPayInfo = baseResult2.getData();
        PayReq request = new PayReq();
        request.appId = wxPayInfo.getAppid();
        request.partnerId = wxPayInfo.getPartnerid();
        request.prepayId = wxPayInfo.getPrepayid();
        request.packageValue = "Sign=WXPay";
        request.nonceStr = wxPayInfo.getNoncestr();
        request.timeStamp = wxPayInfo.getTimestamp();
        request.sign = wxPayInfo.getSign();
        msgApi.sendReq(request);
    }

    // 调起支付宝支付
    private void aliPay(final String orderInfo) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(ConfirmExpertExplainActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = 20100851;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        }).start();
    }

    @SuppressWarnings("all")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            //返回码，标识支付状态，含义如下：9000——订单支付成功 8000——正在处理中 4000——订单支付失败 5000——重复请求 6001——用户中途取消 6002——网络连接出错
            if (msg.what == 20100851) {
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                String payStatus = payResult.getResultStatus();
                if (TextUtils.equals(payStatus, "9000")) {// 判断resultStatus 为9000则代表支付成功
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    ToastUtils.showShort("支付成功");
                    paySuc();

                } else if (TextUtils.equals(payStatus, "6001")) {
                    ToastUtils.showShort("取消支付");
                } else {
                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    ToastUtils.showShort("支付失败");
                }
            }
        }
    };

    private void paySuc() {
        Bundle bundle = new Bundle();
        bundle.putString("from", "expert");// 标识支付来源
        startActivity(PaySuccessActivity.class, bundle);
    }
}